<?php

/**
 * @todo: Refaktorisierung dieser Klasse
 * Gibt es eine entsprechende Implementierung in der Standard PHP Library SPL?
 */
class WSB_DirectoryIterator extends WSB_Fileinfo implements Iterator
{

	/**
	 * Verzeichnis Handler
	 *
	 * @var resoure
	 */
	private $_dir;

	/**
	 * Current dir path
	 *
	 * @var string
	 */
	private $_path;

	/**
	 * Key
	 *
	 * @var integer
	 */
	private $_key;

	/**
	 * Current filename
	 *
	 * @var string
	 */
	private $_file;

	/**
	 * @param string $path
	 */
	public function __construct($path)
	{
	    $path = rtrim($path, '/');
		$this->setInfoClass('WSB_Fileinfo');
		$this->_dir	= is_dir($path) ? opendir($path) : null ;
		$this->_path = $path;
		parent::__construct($path);
	}

	/**
	 * @return void
	 */
	public function __destruct()
	{
		if(is_resource($this->_dir)) {
			closedir($this->_dir);
		}
	}

	/**
	 * @return void
	 */
	public function rewind()
	{
		rewinddir($this->_dir);
		$this->_key = 0;
		$this->_file = readdir($this->_dir);
	}

	/**
	 * @return boolean
	 */
	public function valid()
	{
		return ($this->_file !== false);
	}

	/**
	 * @return integer
	 */
	public function key()
	{
		return $this->_key;
	}

	/**
	 * @return WSB_DirectoryIterator
	 */
	public function current()
	{
		return new self($this->_path.'/'.$this->_file);
	}

	/**
	 * @return void
	 */
	public function next()
	{
		$this->_key++;
		$this->_file = readdir($this->_dir);
	}

	/**
	 * @return boolean
	 */
	public function isDot()
	{
		if((substr($this->_path, -1) == '.') || (substr($this->_path, -2) == '..')) {
			return true;
		}
		return false;
		//return ($this->current()->getFilename() == '.' || $this->current()->getFilename() == '..');
	}

	/**
	 * @return boolean
	 */
	public function isEmpty()
	{
		$isEmpty = true;
		foreach($this AS $fileInfo) {
			if(($fileInfo->isDir() && !$fileInfo->isDot()) || ($fileInfo->isFile())) {
				$isEmpty = false;
				break;
			}
		}
		return $isEmpty;
	}

}
